package Controller;

import Model.AccountDB;
import Model.Post;
import Model.PostDB;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by FreyrWings on 2017/5/30.
 * Json api for requests of multiple posts
 */
public class BlogController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/JavaScript; charset=utf-8");

        if(req.getSession().getAttribute("token")!=null){
            String token = req.getSession().getAttribute("token").toString();
            int accountid = AccountDB.identify(token);// identify the account first
            if(accountid > 0){
                int page = 0;
                String keyword = "";
                try{
                    page = Integer.parseInt(req.getParameter("page"));
                    keyword += req.getParameter("keyword")==null?"":req.getParameter("keyword");
                }
                catch (Exception e){
                    e.printStackTrace();
                }
                JSONObject jsonObject = new JSONObject();
                JSONArray postLists = new JSONArray();
                int total = 0;
                jsonObject.put("total page", PostDB.getPage(keyword, 3));
                for(Post post: PostDB.retrieve(keyword, page>0?page:1, 3)){
                    if(post!=null){
                        total++;
                        JSONObject postObj = new JSONObject();
                        postObj.put("id", post.getId());
                        postObj.put("title", post.getTitle().replaceAll(">", "&gt;").replaceAll("<", "&lt;"));
                        postObj.put("image", post.getImage());
                        postObj.put("description", post.getDescription().replaceAll(">", "&gt;").replaceAll("<", "&lt;"));
                        postObj.put("date", post.getDate());
                        postObj.put("auth", post.getAccountid()==accountid);
                        postObj.put("author", AccountDB.getUsername(post.getAccountid()));
                        postLists.add(postObj);
                    }
                }
                jsonObject.put("total post", total);
                jsonObject.put("posts", postLists);
                jsonObject.put("username", AccountDB.getUsername(accountid));
                resp.getWriter().write(jsonObject.toString());
            }
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
